package com.wondertek.poms.dao.util;

import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.dao.po.BcLog;
import com.wondertek.poms.dao.po.Content;
import com.wondertek.poms.dao.po.ContentFee;
import com.wondertek.poms.dao.po.ForCisLog;
import com.wondertek.poms.dao.po.PrdCont;
import com.wondertek.poms.dao.po.PrdInfo;
import com.wondertek.poms.dao.po.PublishLog;
import com.wondertek.poms.dao.po.SecondClassify;
import com.wondertek.poms.dao.po.SystemConfig;
import com.wondertek.poms.dao.repo.IContentDao;
import com.wondertek.poms.dao.repo.IContentFeeDao;
import com.wondertek.poms.dao.repo.IPrdContDao;
import com.wondertek.poms.dao.repo.IPrdInfoDao;
import com.wondertek.poms.dao.repo.ISecondClassifyDao;
import com.wondertek.poms.dao.repo.ISystemConfigDao;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author chenjijiang
 * @description
 */
@Slf4j
public class ESUtils {
	/**
	 * es服务器的host
	 */
	private static final String host = "127.0.0.1";

	/**
	 * es服务器暴露给client的port
	 */
	private static final int port = 9300;

	/**
	 * es服务器的host
	 */
	private static final String clusterName = "elasticsearch";

	public static String index_name;

	/**
	 * jackson用于序列化操作的mapper
	 */
	static Map<String, String> m = new HashMap<String, String>();

	public static SimpleDateFormat timezoneSdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static TransportClient client;

	static {
		try {
			ISystemConfigDao systemConfigDao = SpringContextHolder.getBean(ISystemConfigDao.class);
			SystemConfig esConfiguration = systemConfigDao.findByCkey("ES_CONFIGURATION");
			String esConfig = "";
			if (StringUtil.isNotBlank(esConfiguration.getValue())) {
				esConfig = esConfiguration.getValue();  //10.200.66.14$9300$elasticsearch$index_prdcontvo
			}
			SystemConfig indexConfig = systemConfigDao.findByCkey("Index_PrdContDao");
			if (StringUtil.isNotBlank(indexConfig.getValue())) {
				index_name = indexConfig.getValue();  //index_prdcontvo_2
			}
			String[] esArray = esConfig.split("\\$");

			String host_name = host;
			int index_port = 9300;
			String cluster_name = clusterName;
			if (esArray.length >= 3) {//如果已配置ES
				host_name = esArray[0];
				index_port = Integer.parseInt(esArray[1]);
				cluster_name = esArray[2];
			}
			// 设置client.transport.sniff为true来使客户端去嗅探整个集群的状态，把集群中其它机器的ip地址加到客户端中，
			Settings settings = Settings.builder().put(m).put("cluster.name", cluster_name).put("client.transport.sniff", true).build();
			client = TransportClient.builder().settings(settings).build();
			client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host_name), index_port));
		} catch (Exception e) {
			log.error("es init error", e);
		}
	}

	// 取得实例
	public static synchronized TransportClient getTransportClient() {
		return client;
	}

	//添加节目
	public static boolean addPrdCont(PrdCont pc, Content content) {
		IContentDao contentDao = SpringContextHolder.getBean(IContentDao.class);
		if (pc == null || pc.getPrdContId() == null || pc.getContentId() == null) {
			log.info("====invalid prdCont found, unable to add:" + pc.getPrdContId() + "contId:" + pc.getContentId());
			return false;
		}
		if (content == null) {
			content = contentDao.findByContentId(pc.getContentId());
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			//System.out.println("====Begin to add ES PrdCont:" + pc.getPrdContId());
			log.info("====Begin to add ES PrdCont:" + pc.getPrdContId());
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("PRD_CONT_ID", pc.getPrdContId())
					.field("BC_STATUS", pc.getBcStatus())
					.field("BC_PERSON", pc.getBcPerson())
					.field("BC_TIME", pc.getBcTime() != null ? timezoneSdf.format(pc.getBcTime()) : null)
					.field("DIST_STATUS", pc.getDistStatus())
					.field("DIST_TIME", pc.getDistTime() != null ? timezoneSdf.format(pc.getDistTime()) : null)
					.field("PUB_STATUS", pc.getPubStatus())
					.field("PUB_TIME", pc.getPubTime() != null ? timezoneSdf.format(pc.getPubTime()) : null)
					.field("PRD_INFO_ID", pc.getPrdInfoId())
					.field("MMS_ID", pc.getMmsId())
					.field("CREATE_TIME", pc.getCreateTime() != null ? timezoneSdf.format(pc.getCreateTime()) : null)
					.field("CONTENT_ID", pc.getContentId())
					.field("FORM_TYPE", pc.getFormType())
					.field("PRODUCT_ID", pc.getProductId())
					.field("RANKVAL", pc.getRankval())
					.field("LONGTITLE", pc.getLongtitle())
					.field("SHORTTITLE", pc.getShorttitle())
					.field("LEVELVAL", pc.getLevelval())
					.field("PRICE", pc.getPrice())
					.field("HITS", pc.getHits())
					.field("ORDER_FLAG", pc.getOrderFlag())
					.field("IS_UPDATING", pc.getIsUpdating())
					.field("PUSH_STATUS", pc.getPushStatus())
					.field("PUSH_TIME", pc.getPushTime())
					.field("OPERATOR", pc.getOperator())
					.field("CIS_STATUS", pc.getCisStatus())
					.field("HAS_PUB", pc.getHasPub())
					.field("IS_SHOW_PRDID", pc.getIsShowPrdId())
					.field("EQUITY_ID", pc.getEquityId())
					.field("IS_PERSON_OPERATION", pc.getIsPersonOperation())
					.field("SELLING_PRICE", pc.getSellingPrice())
					.field("BC_ID", pc.getBcId())
					.field("FILE_ACTION", pc.getFileAction())
					.field("RECALL", pc.getRecall())
					.field("IS_DELETE", pc.getIsDelete())
					.field("BC_REFUSE_REASON", pc.getBcRefuseReason())
					.field("PUB_WEB_STATUS", pc.getPubStatus())
					.field("PUB_WEB_OPER_ID", pc.getPubWebOperId())
					.field("PUB_WEB_TIME", pc.getPubWebTime() != null ? timezoneSdf.format(pc.getPubWebTime()) : null)
					.field("IS_EMERGENCY", pc.getIsEmergency())
					.field("PUBLISH_NO_VOMS_STATUS", pc.getPublishNoVOMSStatus())
					.field("PUBLISH_NO_VOMS_TIME", pc.getPublishNoVOMSTime() != null ? timezoneSdf.format(pc.getPublishNoVOMSTime()) : null)
					.field("SAL_PRODUCT_ID", pc.getSalProductId())
					.field("SAL_CATEGORY", pc.getSalCategory())
					.field("START_TIME", pc.getStartTime())
					.field("END_TIME", pc.getEndTime())
					.field("SAL_PRICE", pc.getSalPrice())
					.field("UPDATE_TIME", pc.getUpdateTime() != null ? timezoneSdf.format(pc.getUpdateTime()) : null)
					.field("ONTRIAL", pc.getOnTrial())
					.startObject("CONTENT")
					.field("ID", content.getId())
					.field("AREA_ID", content.getAreaId())
					.field("AUTHOR", content.getAuthor())
					.field("CATEGORY", content.getCategory())
					.field("CMS_ID", content.getCmsId())
					.field("CONTENT_ID", content.getContentId())
					.field("CONTENT_LISTS", content.getContentLists())
					.field("CONTENT_PLAY_TIME", content.getContentPlayTime())
					.field("COPYRIGHT_ID", content.getCopyrightId())
					.field("CP_ID", content.getCpId())
					.field("CREATE_TIME", content.getCreateTime())
					.field("CREATOR_ID", content.getCreatorId())
					.field("DETAIL", content.getDetail())
					.field("DISPLAY_FILE_LISTS", content.getDisplayFileLists())
					.field("DISPLAY_TYPE", content.getDisplayType())
					.field("FORM_TYPE", content.getFormType())
					.field("KEY_WORDS", content.getKeyWords())
					.field("LABELS", content.getLabels())
					.field("LAST_MODIFY_TIME", content.getLastModifyTime())
//					.field("MEDIA_FILE_LISTS", content.getMediaFileLists())
					.field("NAME", content.getName())
					.field("PRIMARY_KEY_WORD", content.getPrimaryKeyWord())
					.field("PRIORITY", content.getPriority())
					.field("PRODUCT_IDS", content.getProductIds())
					.field("SCENE_FILES", content.getSceneFiles())
					.field("SEQUENCE", content.getSequence())
					.field("SHORT_NAME", content.getShortName())
					.field("STAGE", content.getStage())
					.field("STATUS", content.getStatus())
					.field("SYNC_FILE_PATH", content.getSyncFilePath())
					.field("TYPE", content.getType())
					.field("VERSION", content.getVersion())
					.field("WATER_MASK", content.getWaterMask())
					.field("IS_SUP_WAP", content.getIsSupWap())
					.field("IS_SUP_WWW", content.getIsSupWww())
					.field("IS_SUP_RMS", content.getIsSupRms())
					.field("IS_SUP_H264", content.getIsSupH264())
					.field("UDID", content.getUdid())
					.field("DIRECT_REC_FLAG", content.getDirectRecFlag())
					.field("CDURATION", content.getCduration())
					.field("IS_SUP_RCHD", content.getIsSupRchd())
					.field("DOC_NAME", content.getDocName())
					.field("DISPLAY_NAME", content.getDisplayName())
					.field("ASSET_ID", content.getAssetId())
					.field("N_CPID", content.getNCpid())
					.field("COPYRIGHT_TYPE", content.getCopyrightType())
					.field("MEDIA_LEVEL", content.getMediaLevel())
					.field("SERIAL_CONTENT_ID", content.getSerialContentId())
					.field("SERIAL_SEQUENCE", content.getSerialSequence())
					.field("SERIAL_COUNT", content.getSerialCount())
					.field("BC_ID", content.getBcId())
					.field("ASSIST", content.getAssist())
					.field("COPYRIGHT_OBJECT_ID", content.getCopyrightObjectId())
					.field("COPYRIGHT_CPID", content.getCopyrightCpid())
					.field("BEGIN_DATE", content.getBeginDate())
					.field("END_DATE", content.getEndDate())
					.field("AREA", content.getArea())
					.field("TERMINAL", content.getTerminal())
					.field("INTEGRITY", content.getIntegrity())
					.field("SCARCITY", content.getScarcity())
					.field("CLARITY", content.getClarity())
					.field("SCOPE", content.getScope())
					.field("OUTPUT", content.getOutput())
					.field("FEE_TYPE", content.getFeeType())
					.field("SCORE", content.getScore())
					.field("PUBLISH", content.getPublish())
					.field("OPTIMAL", content.getOptimal())
					.field("CONT_SOURCE_STATUS", content.getContSourceStatus())
					.field("CDN_STATUS", content.getCdnStatus())
					.field("GSLB_STATUS", content.getGslbStatus())
					.field("PLAYBILL_FILE_PATH", content.getPlaybillFilePath())
					.field("NEED_DRM", content.getNeedDRM())
					.field("IS_UPDATING", content.getIsUpdating())
					.field("MOVIE_LIB_ID", content.getMovieLibId())
					.field("IMAGES", content.getImages())
					.field("LIVE_TYPE", content.getLiveType())
					.field("CACHE_CDN_STATUS", content.getCacheCdnStatus())
					.field("AUTHORIZATION_WAY", content.getAuthorizationWay())
					.field("MIGU_PUBLISH", content.getMiguPublish())
					.field("BC_LICENSE", content.getBcLicense())
					.field("INFLUENCE", content.getInfluence())
					.field("ORI_PUBLISH", content.getOriPublish())
					.field("ONLINE_TIME", content.getOnlineTime())
					.field("WAY", content.getWay())
					.field("SUPPORT", content.getSupport())
					.field("CHAIN", content.getChain())
					.field("MIGU_RANK", content.getMiguRank())
					.field("DOUBAN_ID", content.getDoubanId())
//					.field("HAS_VIDEO", (content.getHasVideo() != null && content.getHasVideo()) ? 1 : 0)
					.field("HAS_MOVED", (content.getHasMoved() != null && content.getHasMoved()) ? 1 : 0)
					.field("SERIAL_TRAILING_SEQUENCE", content.getSerialTrailingSequence())
					.field("BLACK_AREA", content.getBlackArea())
					.field("UPDATE_FIELDS", content.getUpdateFields())
					.field("BC_PRIORITY", content.getBcPriority())
					.field("ACCESS_PLATFORM_TYPE", content.getAccessPlatformType())
					.field("DIST_RESULT", content.getDistResult())
					.field("RECOMMENDATION", content.getRecommendation())
					.field("WORKS_TYPE", content.getWorksType())
					.field("RIGHT_TYPE", content.getRightType())
					.field("COPY", content.getCopy())
					.field("KEYWORDS_COPY", content.getKeywordsCopy())
					.field("RECOMMENDATION_COPY", content.getRecommendationCopy())
					.field("NAME_COPY", content.getNameCopy())
					.field("DETAIL_COPY", content.getDetailCopy())
					.field("AUDITION_RECORDS_NUM", content.getAuditionRecordsNum())
					.field("BUSINESS_LICENSE", content.getBusinessLicense())
					.field("CONTENT_LEVEL", content.getContentLevel())
					.field("TV_END_DATE", content.getTvEndDate())
					.field("PRICING", content.getPricing())
					.field("UNIT_PRICING", content.getUnitPricing())
					.field("MONTH_PRICING", content.getMonthPricing())
					.field("CP_RATIO", content.getCpRatio())
					.field("BC_RATIO", content.getBcRatio())
					.field("LAST_TRANSCODE_TIME", content.getLastTranscodeTime())
					.field("MIGU_DBID", content.getMiguDBID())
					.field("MV_ID", content.getMvId())
					.field("MP_ID", content.getMpId())
					.field("MC_ID", content.getMcId())
					.field("IS_MULTILIN_GUAL", content.getIsMultilinGual())
					.field("PLAY_BILL_START_TIME", content.getPlaybillStartTime())
					.field("PLAY_BILL_END_TIME", content.getPlaybillEndTime())
					.field("LIVE_CONTENT_ID", content.getLiveContentId())
					.field("CONTENT_LEVEL", content.getContentLevel())
					.field("IS_MULTI_SCREEN", (content.getIsMultiScreen() != null && content.getIsMultiScreen()) ? 1 : 0)
					.field("NEW_CREATE_TIME", !StringUtil.isNullStr(content.getCreateTime()) ? timezoneSdf.format(sdf.parse(content.getCreateTime())) : null)
					.field("LAST_UPDATE_TIME", !StringUtil.isNullStr(content.getLastModifyTime()) ? timezoneSdf.format(sdf.parse(content.getLastModifyTime())) : null);

			ISecondClassifyDao secondClassifyDao = SpringContextHolder.getBean(ISecondClassifyDao.class);
			List<SecondClassify> scList = secondClassifyDao.findAllByContentId(content.getContentId());
			if (scList != null) {
				prdMapping.startArray("SC");
				for (SecondClassify sc : scList) {
					prdMapping.startObject();
					prdMapping.field("ID", sc.getId());
					prdMapping.field("CLASSIFY_KEY", sc.getClassifyKey());
					prdMapping.field("CLASSIFY_VALUE", sc.getClassifyValue());
					prdMapping.endObject();
				}
				prdMapping.endArray();
			}
			List<Long> list = new ArrayList<>();
			list.add(pc.getPrdInfoId());
			list.add(pc.getPrdContId());
			IContentFeeDao contentFeeDao = SpringContextHolder.getBean(IContentFeeDao.class);
			List<ContentFee> cfList = contentFeeDao.findAllByPomsId(list, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			if (cfList != null) {
				prdMapping.startArray("CONTENT_FEE");
				for (ContentFee cf : cfList) {
					prdMapping.startObject();
					prdMapping.field("SALE_CATEGORY", cf.getSaleCategory());
					prdMapping.field("CHANNEL_PACKAGE_ID", cf.getChannelPackageId());
					prdMapping.endObject();
				}
				prdMapping.endArray();
			}
			IPrdInfoDao prdInfoDao = SpringContextHolder.getBean(IPrdInfoDao.class);
			Optional<PrdInfo> prdInfo = prdInfoDao.findById(pc.getPrdInfoId());
			if (prdInfo.isPresent()) {
				PrdInfo pi = prdInfo.get();
				prdMapping.startObject("PRD_INFO");
				prdMapping.field("MONTH_TYPE", pi.getMonthType());
				prdMapping.field("NUMBER_TYPE", pi.getNumberType());
				prdMapping.field("FREE_TYPE", pi.getFreeType());
				prdMapping.endObject();
			}
			prdMapping.endObject().endObject();
			//log.info(prdMapping.string());
			IndexResponse indexResponse = client.prepareIndex(index_name, "PRDCONTVO").setId(pc.getPrdContId() + "").setSource(prdMapping).execute().actionGet();
		} catch (Exception e) {
			log.error("====Exception!Failed to add PrdCont:" + pc.getPrdContId(), e);
			return false;
		}

		return true;
	}

	//更新节目发布状态
	public static boolean updateVomsPubStatus(Long prdContId, int status) {
		TransportClient client = ESUtils.getTransportClient();
		try {
			if (!isExistPrdCont(prdContId)) {
				log.info("====does not exist PrdCont:" + prdContId);
				return false;
			}

			log.info("====ES Begin to update the VomsPubStatus of PrdCont:" + prdContId);
			UpdateRequest uRequest = new UpdateRequest();
			uRequest.index(index_name);
			uRequest.type("PRDCONTVO");
			uRequest.id(prdContId + "");
			uRequest.doc(XContentFactory.jsonBuilder().startObject()
					.field("PUBLISH_NO_VOMS_STATUS", status)
					.field("PUBLISH_NO_VOMS_TIME", timezoneSdf.format(new Date()))
					.field("UPDATE_TIME", timezoneSdf.format(new Date()))
					.endObject());
			client.update(uRequest.refresh(true)).get();
		} catch (Exception e) {
			//e.printStackTrace();
			log.error("====Exception!Failed to update the VomsPubStatus of PrdCont:" + prdContId, e);
			return false;
		}

		return true;
	}

	//更新节目
	public static boolean updatePrdCont(PrdCont pc) {
		TransportClient client = ESUtils.getTransportClient();
		try {
			IContentDao contentDao = SpringContextHolder.getBean(IContentDao.class);
			Content content = contentDao.findByContentId(pc.getContentId());
			log.info("====ES Begin to update  PrdCont:" + pc.getPrdContId());
			UpdateRequest uRequest = new UpdateRequest();
			uRequest.index(index_name);
			uRequest.type("PRDCONTVO");
			uRequest.id(pc.getPrdContId() + "");
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("BC_STATUS", pc.getBcStatus())
					.field("BC_PERSON", pc.getBcPerson())
					.field("BC_TIME", pc.getBcTime() != null ? timezoneSdf.format(pc.getBcTime()) : null)
					.field("DIST_STATUS", pc.getDistStatus())
					.field("DIST_TIME", pc.getDistTime() != null ? timezoneSdf.format(pc.getDistTime()) : null)
					.field("PUB_STATUS", pc.getPubStatus())
					.field("PUB_TIME", pc.getPubTime() != null ? timezoneSdf.format(pc.getPubTime()) : null)
					.field("PRD_INFO_ID", pc.getPrdInfoId())
					.field("BC_ID", pc.getBcId())
					.field("FILE_ACTION", pc.getFileAction())
					.field("RECALL", pc.getRecall())
					.field("IS_DELETE", pc.getIsDelete())
					.field("BC_REFUSE_REASON", pc.getBcRefuseReason())
					.field("PUB_WEB_STATUS", pc.getPubStatus())
					.field("PUB_WEB_OPER_ID", pc.getPubWebOperId())
					.field("PUB_WEB_TIME", pc.getPubWebTime() != null ? timezoneSdf.format(pc.getPubWebTime()) : null)
					.field("IS_EMERGENCY", pc.getIsEmergency())
					.field("PUBLISH_NO_VOMS_STATUS", pc.getPublishNoVOMSStatus())
					.field("PUBLISH_NO_VOMS_TIME", pc.getPublishNoVOMSTime() != null ? timezoneSdf.format(pc.getPublishNoVOMSTime()) : null)
					.field("SAL_PRODUCT_ID", pc.getSalProductId())
					.field("SAL_CATEGORY", pc.getSalCategory())
					.field("START_TIME", pc.getStartTime())
					.field("END_TIME", pc.getEndTime())
					.field("SAL_PRICE", pc.getSalPrice())
					.field("UPDATE_TIME", pc.getUpdateTime() != null ? timezoneSdf.format(pc.getUpdateTime()) : null)
					.field("ONTRIAL", pc.getOnTrial())
					.startObject("CONTENT")
					.field("STATUS", content.getStatus())
					.field("NAME", content.getName())
					.field("IS_MULTILIN_GUAL", content.getIsMultilinGual())
					.endObject();
			uRequest.doc(prdMapping);
			//log.info("==="+pc.getPublishNoVOMSTime()+"===="+prdMapping.string());
			client.update(uRequest.refresh(true)).get();
		} catch (Exception e) {
			log.error("====Exception!Failed to update PrdCont:" + pc.getPrdContId(), e);
			return false;
		}

		return true;
	}

	public static boolean isExistPrdCont(Long prdContId) {
		TransportClient client = ESUtils.getTransportClient();
		try {
			QueryBuilder qb = QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", prdContId));
			SearchResponse actionGet = client.prepareSearch(ESUtils.index_name).setTypes("PRDCONTVO").setQuery(qb).execute().actionGet();
			if (actionGet != null && actionGet.getHits().getHits().length > 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			log.error("=====exists Exception, false ==========", e);
			return false;
		}
	}

	//为集群添加新的节点
	public static synchronized void addNode(String name) {
		try {
			client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(name), 9300));
		} catch (UnknownHostException e) {
			log.error("add es node error:", e);
		}
	}

	//删除集群中的某个节点
	public static synchronized void removeNode(String name) {
		try {
			client.removeTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(name), 9300));
		} catch (UnknownHostException e) {
			log.error("remove es node error:", e);
		}
	}

	public static void addBcHistory(BcLog bc) {
		if (bc == null || bc.getBcLogId() == null) {
			log.info("====invalid BcHistoryVo found, unable to add:" + bc.getBcLogId());
			return;
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			log.info("====Begin to add ES BcHistoryVo:" + bc.getBcLogId());
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("BC_LOG_ID", bc.getBcLogId())
					.field("PRD_CONT_ID", bc.getPrdContId())
					.field("BC_STATUS", bc.getBcStatus())
					.field("BC_PERSON", bc.getBcPerson())
					.field("BC_TIME", timezoneSdf.format(bc.getBcTime()))
					.field("BC_REFUSE_REASON", bc.getBcRefuseReason())
					.field("CONTENT_ID", bc.getContentId())
					.field("BC_ID", bc.getBcId())
					.field("MMS_ID", bc.getMmsId());

			if (bc.getContentId() != null) {
				IContentDao contentDao = SpringContextHolder.getBean(IContentDao.class);
				Content content = contentDao.findByContentId(String.valueOf(bc.getContentId()));
				prdMapping.field("DISPLAY_TYPE", content.getDisplayType());
				prdMapping.field("NAME", content.getName());
			}

			if (bc.getPrdContId() != null) {
				IPrdContDao prdContDao = SpringContextHolder.getBean(IPrdContDao.class);
				Optional<PrdCont> prdContOptional = prdContDao.findById(bc.getPrdContId());
				if (prdContOptional.isPresent()) {
					PrdCont prdCont = prdContOptional.get();
					//prdMapping.field("BC_ID", prdCont.getBcId());
					prdMapping.field("PRD_INFO_ID", prdCont.getPrdInfoId());
				}
			}

			prdMapping.endObject();
			//log.info(prdMapping.string());

			IndexResponse indexResponse = client.prepareIndex(index_name, "BcHisVO").setSource(prdMapping).execute().actionGet();
		} catch (Exception e) {
			log.error("====Exception!Failed to add BcHistoryVo:" + bc.getBcLogId(), e);
		}
	}

	public static void addBcHistory(Long prdContId, Long bcId) {
		if (prdContId == null) {
			log.info("====unable to add BcHistoryVo , prdContId == null");
			return;
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			IPrdContDao prdContDao = SpringContextHolder.getBean(IPrdContDao.class);
			log.info("====Begin to add ES BcHistoryVo:" + prdContId);
			PrdCont pc = prdContDao.findById(prdContId).get();
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("PRD_CONT_ID", pc.getPrdContId())
					.field("BC_STATUS", pc.getBcStatus())
					.field("BC_PERSON", pc.getBcPerson())
					.field("BC_TIME", timezoneSdf.format(pc.getBcTime()))
					.field("BC_REFUSE_REASON", pc.getBcRefuseReason())
					.field("CONTENT_ID", pc.getContentId())
					.field("MMS_ID", pc.getMmsId())
					.field("BC_ID", bcId)
					.field("PRD_INFO_ID", pc.getPrdInfoId());

			if (pc.getContentId() != null) {
				IContentDao contentDao = SpringContextHolder.getBean(IContentDao.class);
				Content content = contentDao.findByContentId(pc.getContentId());
				prdMapping.field("DISPLAY_TYPE", content.getDisplayType());
				prdMapping.field("NAME", content.getName());
			}

			prdMapping.endObject();
			//log.info(prdMapping.string());
			IndexResponse indexResponse = client.prepareIndex(index_name, "BcHisVO").setSource(prdMapping).execute().actionGet();
		} catch (Exception e) {
			log.info("====Exception!Failed to add BcHistoryVo:" + prdContId, e);
		}
	}

	public static void addPublishLog(PublishLog pub) {
		if (pub == null) {
			log.info("====null PublishLog found, unable to add");
			return;
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			log.info("====Begin to add ES PublishLog:" + pub.getId());
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("ID", pub.getId())
					.field("PRD_CONT_ID", pub.getPrdContId())
					.field("CONT_ID", pub.getContId())
					.field("STATUS", pub.getStatus())
					.field("CREATE_USER_NAME", pub.getCreateUserName())
					.field("CREATE_DATE", timezoneSdf.format(pub.getCreateTime()))
					.field("PRD_INFO_ID", pub.getPrdInfoId())
					.field("CONT_NAME", pub.getContName())
					.field("OPR_CODE", pub.getOprCode())
					.field("REMARKS", pub.getRemarks())
					.endObject();
			log.info(prdMapping.string());
			IndexResponse indexResponse = client.prepareIndex(index_name, "PublishLog").setId(pub.getId().toString()).setSource(prdMapping).execute().actionGet();
		} catch (Exception e) {
			log.info("====Exception!Failed to add PublishLog:" + pub.getId(), e);
		}

	}

	/**
	 * @param forCisLog
	 */
	public static void addForCisLog(ForCisLog forCisLog) {
		if (forCisLog == null) {
			log.info("====null forCisLog found, unable to add");
			return;
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			log.info("====Begin to add ES PublishLog:" + forCisLog.getId());
			XContentBuilder prdMapping = XContentFactory.jsonBuilder().startObject()
					.field("ID", forCisLog.getId())
					.field("AUDIT_STATUS", forCisLog.getAuditStatus())
					.field("CREATE_TIME", timezoneSdf.format(forCisLog.getCreateTime()))
					.field("IS_FREE_TRIAL", forCisLog.getIsFreetrial())
					.field("MEDIA_FILE_ID", forCisLog.getMediaFileId())
					.field("OPERATION", forCisLog.getOperation())
					.field("PRD_CONT_ID", forCisLog.getPrdContId())
					.field("RESPONSE_MESSAGE", forCisLog.getResponseMessage())
					.field("RESPONSE_STATUS", forCisLog.getResponseStatus())
					.field("RESPONSE_TIME", !StringUtil.isNullStr(forCisLog.getResponseTime()) ? timezoneSdf.format(sdf.parse(forCisLog.getResponseTime())) : null)
					.field("UUID", forCisLog.getUuid())
					.endObject();
			log.info(prdMapping.string());
			IndexResponse indexResponse = client.prepareIndex(index_name, "ForCisLog").setId(forCisLog.getId().toString()).setSource(prdMapping).execute().actionGet();
		} catch (Exception e) {
			log.info("====Exception!Failed to add forCisLog:" + forCisLog.getId(), e);
		}


	}

	public static void deletePrdCont(Long prdContId) {
		if (prdContId == null) {
			log.info("====PrdCont does not exist, unable to delete " + prdContId);
			return;
		}

		TransportClient client = ESUtils.getTransportClient();
		try {
			log.info("====Begin to delete ES PrdCont:" + prdContId);
			DeleteResponse indexResponse = client.prepareDelete(index_name, "PRDCONTVO", prdContId.toString()).setRefresh(true).execute().actionGet();
		} catch (Exception e) {
			log.info("====Exception!Failed to delete PrdCont:" + prdContId, e);
		}
	}

}
